import wsgiref.handlers
import sys
import os
import string
import codecs
import geohash
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

#from django.autils.translation import ugettext as _


from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from models import *
from utilities import *
from dbutilities import *
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.runtime import *
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images

_DEBUG = True

webapp.template.register_template_library('customfilters')

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'application_name': 'Clanty',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))



class BulkData(BaseRequestHandler):
  def get(self,counter):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0

   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   counter = int(counter)
   fileurl="worten.csv"
   fileHandle = open (fileurl, 'r')
   fileList = fileHandle.readlines()
   line = fileList[counter]
   arrayline=line.decode( "utf-8" ).replace('"','').split(';')
   termmanager = TermManager()
   attributes = []
   article = unicode(arrayline[0]).strip()

   if article == 'die':
     attributes.append('feminine')
   elif article == 'der':
     attributes.append('masculine')   
   elif article == 'der':
     attributes.append('neutral')

   word = unicode(arrayline[1]).strip()
   prefix = ''
   translate = unicode(arrayline[2]).strip()
   tag = unicode(arrayline[3]).strip()
   url = word.lower().replace(' ','-').replace('(','').replace(')','').replace('?','')
   level = 'Basic'
   tagurl = tag.lower().replace(' ','-').replace('(','').replace(')','').replace('?','')
   tags = []
   if tag != '':
     tagmanager = TagManager()
     tagmanager.CheckTag(tag,tagurl,'de')
     tags.append(tag)
   
   language = Language.get('agpoZWFkZXJsaW5lchALEghMYW5ndWFnZRip0zYM')
   strtype = unicode(arrayline[4]).strip()
   counter = int(counter) + 1
   if strtype == 'Ausdruck':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRih5SMM')
   elif strtype == 'Substantiv':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRiRlyMM')
   elif strtype == 'Verb':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRjJriMM')
   elif strtype == 'Adjektiv':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRiBxiMM')
   elif strtype == 'Adverb':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRiZviMM')
   elif strtype == 'Busche':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRiJ7SMM')
   elif strtype == 'Fragenpartikel':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRiBhzgM')
   elif strtype == 'Praposition':
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRjawzYM')
   else:
     termtype = TermType.get('agpoZWFkZXJsaW5lchALEghUZXJtVHlwZRid_zcM')

   term = termmanager.NewTerm(word,prefix,translate,url,level,tags,language,termtype,attributes)

 
   template_values = {
     'lang': 'en',
     'tag': tag,
     'login': True,
     'term': term,
     'counter': counter,
     'customuser': customuser
   }
   self.generate('bulkdata.html', template_values)


     
class DeleteFilm(BaseRequestHandler):
  def get(self,filmid):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   film=Film.get(filmid)
   film.delete()
   self.redirect("/films/", False)
     


class DetailFilm(BaseRequestHandler):
  def get(self,filmurl):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    user = users.get_current_user()
    queryuser = CustomUser.all()
    queryuser.filter(' user = ', user)
    customusers = queryuser.fetch(1)
    customuser = customusers[0]
    queryfilms = Film.all()
    queryfilms.filter(' customuser = ', customuser)
    queryfilms.filter(' url = ', filmurl)
    films = queryfilms.fetch(1)
    film = films[0]
    querypeople = PersonxFilm.all()
    querypeople.filter('film = ',film)
    people = querypeople.fetch(100)
    template_values = {
      'login': True,
      'customusers': customusers,
      'customuser': customuser,
      'people': people,
      'lang': 'en',
      'film': film
    }
    self.generate('film.html', template_values)


class Index(BaseRequestHandler):
  def get(self,lang):
    logincontrol = LoginControl()
    customuser = logincontrol.CheckAccess('admin')
    if customuser.role!='admin':
      login = False
    else:
      access = logincontrol.CheckLogin('admin',self)
      login = True

    queryterms = Term.all()

    if lang != 'all':
      querylanguage = Language.all()
      querylanguage.filter('url = ', lang)
      languages = querylanguage.fetch(1)
      language = languages[0]
      queryterms.filter(' language = ', language)

    queryterms.order('-pub_date')
    queryterms.order('word')
    terms = queryterms.fetch(5)
    template_values = {
      'login': login,
      'terms': terms,
      'lang': lang,
      'customuser': customuser
    }
    self.generate('index.html', template_values)



class IndexRedirect(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    customuser = logincontrol.CheckAccess('admin')
    if customuser.role!='admin':
      login = False
    else:
      access = logincontrol.CheckLogin('admin',self)
      login = True
    self.redirect('/en')



class Films(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    user = users.get_current_user()
    queryuser = CustomUser.all()
    queryuser.filter(' user = ', user)
    customusers = queryuser.fetch(1)
    customuser = customusers[0]
    queryfilms = Film.all()
    if customuser.url=='marivi':
      tmpcustomuser = CustomUser.get('agpoZWFkZXJsaW5lchILEgpDdXN0b21Vc2VyGOX0CQw')
      queryfilms.filter(' customuser = ', tmpcustomuser)
    else:
      queryfilms.filter(' customuser = ', customuser)
    queryfilms.order('url')
    films = queryfilms.fetch(500)

    querygenres = Genre.all()
    genres = querygenres.fetch(100)

    template_values = {
      'login': True,
      'customuser': customuser,
      'genres': genres,
      'lang': 'en',
      'films': films
    }
    self.generate('films.html', template_values)



class FilmsByGenre(BaseRequestHandler):
  def get(self,genreurl):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    user = users.get_current_user()
    queryuser = CustomUser.all()
    queryuser.filter(' user = ', user)
    customusers = queryuser.fetch(1)
    customuser = customusers[0]
    queryfilms = Film.all()
    queryfilms.filter(' customuser = ', customuser)
    queryfilms.filter(' genresurl = ', genreurl)
    queryfilms.order('url')
    films = queryfilms.fetch(500)

    querygenres = Genre.all()
    querygenres.filter(' url = ', genreurl)
    genres = querygenres.fetch(100)
    genre = genres[0]

    querygenres = Genre.all()
    genres = querygenres.fetch(100)

    template_values = {
      'login': True,
      'customuser': customuser,
      'genres': genres,
      'genre': genre,
      'lang': 'en',
      'films': films
    }
    self.generate('filmsbygenre.html', template_values)


class GetTags(BaseRequestHandler):
  def get(self,lang):
    term = self.request.get('term').lower()
    querylanguage = Language.all()
    querylanguage.filter('url = ', lang)
    languages = querylanguage.fetch(1)
    language = languages[0]

    querytags = Tag.all()
    querytags.filter(' language = ', language)

    if term != '':
      querytags.filter(' letters = ', term)

    tags = querytags.fetch(20)
    template_values = {
      'tags': tags,
      'lang': 'en',
      'login': True
    }
    self.generate('gettags.json', template_values)



class DetailPerson(BaseRequestHandler):
  def get(self,personurl):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    user = users.get_current_user()
    queryuser = CustomUser.all()
    queryuser.filter(' user = ', user)
    customusers = queryuser.fetch(1)
    customuser = customusers[0]
    queryfilms = Film.all()
    queryfilms.filter(' customuser = ', customuser)
    queryfilms.filter(' castingurl = ', personurl)
    queryfilms.order('url')
    films = queryfilms.fetch(500)
    queryperson = Person.all()
    queryperson.filter('url = ',personurl)
    people = queryperson.fetch(1)
    person = people[0]

    querygenres = Genre.all()
    genres = querygenres.fetch(100)

    template_values = {
      'login': True,
      'customuser': customuser,
      'genres': genres,
      'person': person,
      'lang': 'en',
      'films': films
    }
    self.generate('filmsbyperson.html', template_values)



class EditFilm(BaseRequestHandler):
  def get(self,filmid):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   film=Film.get(filmid)
   template_values = {
     'login': True,
     'film': film,
     'lang': 'en',
     'customuser': customuser
   }
   
   self.generate('editfilm.html', template_values)

     
  def post(self,filmid):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   
   if self.request.get("save")!='':
     film = Film.get(filmid)
     title = self.request.get("title")
     url = self.request.get("title").lower().strip().replace("'","").replace(' ','-').replace(',','').replace(':','').replace('!','')
     directorname = self.request.get("director")
     directorurl = directorname.lower().strip().replace(' ','-').replace(',','').replace("'","").replace('!','').replace(':','').replace('.','').replace('&','and')
     txtcasting = self.request.get("actors")
     casting = txtcasting.split(',')       
     castingurl = []
     queryperson = Person.all()
     queryperson.filter('url = ',directorurl)    
     if queryperson.count()==0:
       director = Person()
       director.name = directorname
       director.url = directorurl
       director.put()
     else:
       directors = queryperson.fetch(1)
       director = directors[0]

     for person in casting:
       personurl = person.lower().strip().replace(' ','-').replace(',','').replace("'","").replace('!','').replace(':','').replace('.','').replace('&','and')
       castingurl.append(personurl)
       queryperson = Person.all()
       queryperson.filter('url = ',personurl)
       if queryperson.count()==0:
          newperson = Person()
          newperson.name = person
          newperson.url = personurl
          newperson.put()

     if directorurl not in castingurl:
       castingurl.append(directorurl)
     
     image = self.request.get("image")
     year = int(self.request.get("year"))
     plot = self.request.get("plot")
     genres = self.request.get("genres").split(',')

     genresurl = []
     for genre in genres:
       genreurl = genre.lower().strip().replace(' ','-').replace(',','').replace("'","").replace('!','').replace(':','').replace('.','').replace('&','and')
       genresurl.append(genreurl)
       querygenres = Genre.all()
       querygenres.filter('url = ',genreurl)
       if querygenres.count()==0:
         newgenre = Genre()
         newgenre.name = genre
         newgenre.url = genreurl
         newgenre.put()

     film.title = title
     film.url = url
     film.year = year
     film.genres = genres
     film.genresurl = genresurl
     film.director = director
     film.casting = casting
     film.castingurl = castingurl
     film.image = image
     film.customuser = customuser
     film.plot = plot
     film.put()

     self.redirect("/film/" + str(film.url), True)



class Login(BaseRequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   self.redirect('/')




class MarkFavourite(BaseRequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   termtype = ''
   key = self.request.get('key');
   if key!='':
     term = Term.get(key)
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if customuser.url == 'irra':
     if term.fav1:
       term.fav1 = False
     else:
       term.fav1 = True
   elif customuser.url == 'alvaro':
     if term.fav2:
       term.fav2 = False
     else:
       term.fav2 = True
   term.put()


   if customuser.url == 'irra':
     if term.fav1:
       termtype = 'fav1'
     elif term.fav2:
       termtype = 'fav2'
     else:
       termtype = 'nofav'

   elif customuser.url == 'alvaro':
     if term.fav2:
       termtype = 'fav2'
     elif term.fav1:
       termtype = 'fav1'
     else:
       termtype = 'nofav'
   
   template_values = {
     'key': key,
     'lang': 'en',
     'type': termtype,
     'login': True,
     'customuser': customuser
   }
   self.generate('markfavourite.json', template_values)


     
class NewFilm(BaseRequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   template_values = {
     'login': True,
     'lang': 'en',
     'customuser': customuser
   }
   self.generate('newfilm.html', template_values)

     
  def post(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if self.request.get("save")!='':
     film = Film()
     title = self.request.get("title")
     url = self.request.get("title").lower().strip().replace("'","").replace(' ','-').replace(',','').replace(':','').replace('!','')
     directorname = self.request.get("director")
     directorurl = directorname.lower().strip().replace(' ','-').replace(',','').replace("'","").replace('!','').replace(':','').replace('.','').replace('&','and')
     txtcasting = self.request.get("actors")
     casting = txtcasting.split(',')       
     castingurl = []
     queryperson = Person.all()
     queryperson.filter('url = ',directorurl)    
     if queryperson.count()==0:
       director = Person()
       director.name = directorname
       director.url = directorurl
       director.put()
     else:
       directors = queryperson.fetch(1)
       director = directors[0]

     for person in casting:
       personurl = person.lower().strip().replace(' ','-').replace(',','').replace("'","").replace('!','').replace(':','').replace('.','').replace('&','and')
       castingurl.append(personurl)
       queryperson = Person.all()
       queryperson.filter('url = ',personurl)
       if queryperson.count()==0:
          newperson = Person()
          newperson.name = person
          newperson.url = personurl
          newperson.put()

     if directorurl not in castingurl:
       castingurl.append(directorurl)
     
     image = self.request.get("image")
     year = int(self.request.get("year"))
     plot = self.request.get("plot")
     genres = self.request.get("genres").split(',')

     genresurl = []
     for genre in genres:
       genreurl = genre.lower().strip().replace(' ','-').replace(',','').replace("'","").replace('!','').replace(':','').replace('.','').replace('&','and')
       genresurl.append(genreurl)
       querygenres = Genre.all()
       querygenres.filter('url = ',genreurl)
       if querygenres.count()==0:
         newgenre = Genre()
         newgenre.name = genre
         newgenre.url = genreurl
         newgenre.put()

     film.title = title
     film.url = url
     film.year = year
     film.genres = genres
     film.genresurl = genresurl
     film.director = director
     film.casting = casting
     film.castingurl = castingurl
     film.image = image
     film.customuser = customuser
     film.plot = plot
     film.put()

     self.redirect("/film/" + str(film.url), True)



class Printable(BaseRequestHandler):
  def get(self,lang):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True

   if self.request.get("page") == '':
     page = 1
   else:
     page = int(self.request.get("page"))

   limit = 200
   offset = limit * (page-1)

   queryterms = Term.all()

   if lang != 'all':
     querylanguage = Language.all()
     querylanguage.filter('url = ', lang)
     languages = querylanguage.fetch(1)
     language = languages[0]
     queryterms.filter(' language = ', language)

   queryterms.order('url')
   if lang == 'de':
     configuration = Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGMnvNww')
   else:
     configuration = Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGLH3Nww')
   
   numpages = int(math.ceil(int(configuration.value)/limit)) + 2
   pages = range(1,numpages)
   terms = queryterms.fetch(limit,offset)
   pagestext = []
   for apage in pages:
     tmppage = {}
     querypagination = Pagination.all()
     strkey = 'page-' + str(apage) + '-' + lang
     querypagination.filter('name = ',strkey)
     paginations = querypagination.fetch(1)
     if len(paginations)==0:
       pagination = Pagination()
       pagination.name = strkey
       pagination.first = terms[0].prefix + terms[0].word
       pagination.last = terms[len(terms)-1].prefix + terms[len(terms)-1].word
       pagination.put()
     else:
       pagination = paginations[0]
       if page == apage:
         pagination.first = terms[0].prefix + terms[0].word
         pagination.last = terms[len(terms)-1].prefix + terms[len(terms)-1].word
         pagination.put()

     tmppage['first'] = pagination.first
     tmppage['last'] = pagination.last
     pagestext.append(tmppage)
     
   termmanager = TermManager()
   querytermtype = TermType.all()
   termtypes = querytermtype.fetch(20)
   template_values = {
     'lang': lang,
     'termtype': False,
     'login': login,
     'termtypes': termtypes,
     'customuser': customuser,
     'pagestext': pagestext,
     'page': page,
     'terms': terms
   }

   self.generate('printable.html', template_values)



class ProxyImagesImdb(BaseRequestHandler):
  def get(self):
    fileurl = self.request.get("href")
    try:
      result = urlfetch.fetch(fileurl)
    except DeadlineExceededError:
      data = ''
    except urlfetch.DownloadError:
      data = ''
    except e:
      data = ''
    self.response.headers['Content-Type'] = "image/jpeg"
    self.response.out.write(result.content)



class TagAction(BaseRequestHandler):
  def get(self,tagid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     tagmanager = TagManager()
     tag = Tag.get(tagid)
     tagmanager.DeleteTag(tagid)
     self.redirect("/tags/"+tag.language.url, False)
     return 1
   elif action=='edit':
     tag=Tag.get(tagid)
     querylanguage = Language.all()
     querylanguage.order('url')
     languages = querylanguage.fetch(100)
     template_values = {
       'login': True,
       'customuser': customuser,
       'languages': languages,
       'language': tag.language.url,
       'lang': tag.language.url,
       'tag': tag,
       'path': "/tags/"+tagid+"/save/",
     }
   elif action=='new':
     tagtype = self.request.get('type')
     querylanguage = Language.all()
     querylanguage.order('url')
     languages = querylanguage.fetch(100)
     template_values = {
       'login': True,
       'lang': 'en',
       'customuser': customuser,
       'languages': languages,
       'path': "/tags//save/",
     }

   self.generate('tag.html', template_values)
     
  def post(self,tagid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if self.request.get("save")!='':
       error = False
       name = self.request.get("name")
       url = self.request.get("url")
       lang = self.request.get("language")
       if tagid=='':
         querytags = Tag.all()
         querytags.filter(' url = ', url)
         if querytags.count()>0:
           error = True
           errormessage = 'That tag is already in the tag list'

         if name== '':
           error = True
           errormessage = 'You must indicate a tag name'
       
       if not error:
         tagmanager = TagManager()
         if tagid!='':
           tag = tagmanager.EditTag(tagid,name,url,lang)
         else:
           tag =tagmanager.NewTag(name,url,lang)
         self.redirect("/tags/"+lang, True)
       else:
         if tagid=='':
           tag=''
         template_values = {
           'login': True,
           'customuser': customuser,
           'tag': tag,
           'lang': 'en',
           'error': True,
           'errormessage': errormessage,
           'path': "/tags/"+tagid+"/save/",
         }
         self.generate('tag.html', template_values)



class TagList(BaseRequestHandler):
  def get(self,lang):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True
   
   querylanguage = Language.all()
   querylanguage.filter('url = ', lang)
   languages = querylanguage.fetch(1)
   if len(languages)>0:
    language = languages[0]

   querytags = Tag.all()

   if lang!= 'all':
     querytags.filter('language = ',language)
   querytags.order('url')
   tags = querytags.fetch(500)

   template_values = {
     'termtype': False,
     'login': login,
     'lang': lang,
     'customuser': customuser,
     'tags': tags
   }

   self.generate('tags.html', template_values)



class TagListRedirect(BaseRequestHandler):
  def get(self):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True
   
   self.redirect("/tags/en")



class VocabularyAction(BaseRequestHandler):
  def get(self,termid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     term=Term.get(termid)
     lang=term.language.url
     termmanager = TermManager()
     termmanager.DeleteTerm(termid)
     self.redirect("/vocabulary/"+lang, False)
     return 1
   elif action=='edit':
     term=Term.get(termid)
     lang=term.language.url
     querylanguage = Language.all()
     querylanguage.order('url')
     languages = querylanguage.fetch(100)
     querytermtype = TermType.all()
     querytermtype.order('url')
     termtypes = querytermtype.fetch(100)
     template_values = {
       'login': True,
       'customuser': customuser,
       'term': term,
       'lang': lang,
       'prefix': term.prefix,
       'languages': languages,
       'termtypes': termtypes,
       'termtype': term.termtype.url,
       'language': term.language.url,
       'path': "/vocabulary/"+termid+"/save/",
     }
   elif action=='new':
     lang = termid 
     termtype = self.request.get('type')
     querylanguage = Language.all()
     querylanguage.order('url')
     languages = querylanguage.fetch(100)
     querytermtype = TermType.all()
     querytermtype.order('url')
     termtypes = querytermtype.fetch(100)
     template_values = {
       'login': True,
       'prefix': '',
       'lang': lang,
       'customuser': customuser,
       'languages': languages,
       'termtypes': termtypes,
       'termtype': termtype,
       'language': lang,
       'path': "/vocabulary//save/",
     }

   self.generate('term.html', template_values)
     
  def post(self,termid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':

     if self.request.get("save")!='':
       error = False
       prefix=''
       attributes = []
       word = self.request.get("word")
       listword = word.split('/')
       url = self.request.get("url")
       level = self.request.get("level")
       
       
       if len(listword)>1:
         prefix = listword[0]
         word = listword[1]
         url = url.replace('/','')

       
       translate = self.request.get("translate")
       translate2 = self.request.get("translate2")
       translate3 = self.request.get("translate3")

       tmplist = self.request.get("tags").split(',')
       tags= []
       language = Language.get(self.request.get("language"))

       for txttag in tmplist:
         txttagurl=txttag.strip().lower()
         tagmanager = TagManager()
         if txttag != '':
           tag = tagmanager.CheckTag(txttag,txttagurl,language.url) 
           tags.append(tag.name)

       transitivity = self.request.get("transitivity")
       if transitivity=='transitive':
          attributes.append('transitive')
       elif transitivity == 'intransitive':
         attributes.append('intransitive')

       regularity = self.request.get("regularity")
       if regularity=='regular':
          attributes.append('regular')
       elif regularity == 'iregular':
         attributes.append('iregular')

       gender = self.request.get("gender")
       if gender=='masculine':
          attributes.append('masculine')
       elif gender == 'feminine':
         attributes.append('feminine')
       elif gender == 'neutral':
         attributes.append('neutral')

       case = self.request.get("case")
       if case=='accusative':
          attributes.append('accusative')
       elif case == 'dative':
         attributes.append('dative')
       elif case == 'nominative':
         attributes.append('nominative')

       reflexive = self.request.get("reflexive")
       if reflexive!='':
          attributes.append('reflexive')

       if prefix!='':
          attributes.append('separable')

       termtype = TermType.get(self.request.get("termtype"))
       if termid=='':
         queryterm = Term.all()
         queryterm.filter(' url = ', url)
         if queryterm.count()>0:
           error = True
           errormessage = 'That word is already in the vocabulary'
       
       if not error:
         termmanager = TermManager()
         try:
           tmpterm=Term.get(termid)
           term = termmanager.EditTerm(termid,word,prefix,translate,translate2,translate3,url,level,tags,language,termtype,attributes)
         except:
           term = termmanager.NewTerm(word,prefix,translate,translate2,translate3,url,level,tags,language,termtype,attributes)
           
         self.redirect("/vocabulary/"+language.url+"/new/", True)
       else:
         querylanguage = Language.all()
         querylanguage.order('url')
         languages = querylanguage.fetch(100)
         querytermtype = TermType.all()
         querytermtype.order('url')
         termtypes = querytermtype.fetch(100)
         if termid=='':
           term = ''
           lang = language.url
         else:
           termtype = term.termtype.url
           language = term.language.url
           lang = language
         template_values = {
           'login': True,
           'customuser': customuser,
           'term': '',
           'lang': lang,
           'prefix': '',
           'error': True,
           'errormessage': errormessage,
           'languages': languages,
           'termtypes': termtypes,
           'termtype': termtype,
           'language': language,
           'path': "/vocabulary/"+termid+"/save/",
         }
         self.generate('term.html', template_values)



class VocabularyFavourite(BaseRequestHandler):
  def get(self,lang):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True


   queryterms = Term.all()
   if lang == 'en':
     language = Language.get('agpoZWFkZXJsaW5lchALEghMYW5ndWFnZRipjyMM')
     queryterms.filter(' language = ', language)
   elif lang == 'de':
     language = Language.get('agpoZWFkZXJsaW5lchALEghMYW5ndWFnZRip0zYM')
     queryterms.filter(' language = ', language)
   elif lang == 'fr':
     language = Language.get('agpoZWFkZXJsaW5lchALEghMYW5ndWFnZRjpzSMM')
     queryterms.filter(' language = ', language)
   
   if customuser.url == 'irra':
     queryterms.filter('fav1', True)
   elif customuser.url == 'alvaro':
     queryterms.filter('fav2', True)

   queryterms.order('url')
   terms = queryterms.fetch(500)
   querytermtype = TermType.all()
   termtypes = querytermtype.fetch(20)
   template_values = {
     'lang': lang,
     'termtype': False,
     'login': login,
     'termtypes': termtypes,
     'customuser': customuser,
     'terms': terms
   }

   self.generate('terms.html', template_values)




class VocabularyList(BaseRequestHandler):
  def get(self,lang):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True

   if self.request.get("page") == '':
     page = 1
   else:
     page = int(self.request.get("page"))

   limit = 50
   offset = limit * (page-1)

   queryterms = Term.all()

   if lang != 'all':
     querylanguage = Language.all()
     querylanguage.filter('url = ', lang)
     languages = querylanguage.fetch(1)
     language = languages[0]
     queryterms.filter(' language = ', language)

   queryterms.order('url')
   if lang == 'de':
     configuration = Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGMnvNww')
   else:
     configuration = Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGLH3Nww')
   
   numpages = int(math.ceil(int(configuration.value)/limit)) + 1
   pages = range(1,numpages)
   terms = queryterms.fetch(limit,offset)
   pagestext = []
   for apage in pages:
     tmppage = {}
     querypagination = Pagination.all()
     strkey = 'page-' + str(apage) + '-' + lang
     querypagination.filter('name = ',strkey)
     paginations = querypagination.fetch(1)
     if len(paginations)==0:
       pagination = Pagination()
       pagination.name = strkey
       pagination.first = terms[0].prefix + terms[0].word
       pagination.last = terms[len(terms)-1].prefix + terms[len(terms)-1].word
       pagination.put()
     else:
       pagination = paginations[0]
       if page == apage:
         pagination.first = terms[0].prefix + terms[0].word
         pagination.last = terms[len(terms)-1].prefix + terms[len(terms)-1].word
         pagination.put()

     tmppage['first'] = pagination.first
     tmppage['last'] = pagination.last
     pagestext.append(tmppage)
     
   termmanager = TermManager()
   querytermtype = TermType.all()
   termtypes = querytermtype.fetch(20)
   template_values = {
     'lang': lang,
     'termtype': False,
     'login': login,
     'termtypes': termtypes,
     'customuser': customuser,
     'pagestext': pagestext,
     'page': page,
     'terms': terms
   }

   self.generate('terms.html', template_values)




class VocabularyListRedirect(BaseRequestHandler):
  def get(self):
    self.redirect('/vocabulary/en')



class VocabularyListByType(BaseRequestHandler):
  def get(self,termtypeurl,lang):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True

   if self.request.get("page") == '':
     page = 1
   else:
     page = int(self.request.get("page"))

   limit = 200
   offset = limit * (page-1)
   querytermtype = TermType.all()
   querytermtype.filter('url =', termtypeurl)
   termtypes = querytermtype.fetch(1)
   termtype = termtypes[0]
   queryterms = Term.all()
   queryterms.filter('termtype =', termtype)
   if lang != 'all':
     querylanguage = Language.all()
     querylanguage.filter('url = ', lang)
     languages = querylanguage.fetch(1)
     language = languages[0]
     queryterms.filter(' language = ', language)

   queryterms.order('url')
   terms = queryterms.fetch( limit, offset)
   querytermtype = TermType.all()
   termtypes = querytermtype.fetch(20)
   if lang == 'de':
     configuration = Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGMnvNww')
   else:
     configuration = Configuration.get('agpoZWFkZXJsaW5lchULEg1Db25maWd1cmF0aW9uGLH3Nww')
   
   #numpages = math.ceil(int(configuration.value)/limit)
   #pages = range(1,numpages)
   pages = []

   template_values = {
     'pages': pages,
     'page': page,
     'lang': lang,
     'login': login,
     'termtype': termtype,
     'termtypes': termtypes,
     'customuser': customuser,
     'terms': terms
   }

   self.generate('terms.html', template_values)




class VocabularyListByTags(BaseRequestHandler):
  def get(self,tagurl,lang):
   logincontrol = LoginControl()
   customuser = logincontrol.CheckAccess('admin')
   if customuser.role!='admin':
     login = False
   else:
     access = logincontrol.CheckLogin('admin',self)
     login = True

   querytags = Tag.all()
   querytags.filter('url =', tagurl)
   tags = querytags.fetch(1)

   queryterms = Term.all()   
   
   if len(tags)>0:
     querylanguage = Language.all()
     querylanguage.filter('url = ', lang)
     languages = querylanguage.fetch(1)
     language = languages[0]

     tag = tags[0]
     queryterms.filter('tags =', tag.name)
     queryterms.filter('language =', language)
   else:
     tag = ''

   queryterms.order('url')
   terms = queryterms.fetch(500)

   template_values = {
     'lang': lang,
     'login': login,
     'tag': tag,
     'customuser': customuser,
     'terms': terms
   }

   self.generate('terms.html', template_values)




def real_main():
  application = webapp.WSGIApplication([
                                        #Home
                                        ('/', IndexRedirect),
                                        ('/gettags/(en)', GetTags),
                                        ('/gettags/(de)', GetTags),
                                        ('/gettags/(fr)', GetTags),
                                        ('/markfavourite', MarkFavourite),
                                        ('/bulkdata/(\d*)', BulkData),
                                        ('/(en)', Index),
                                        ('/(de)', Index),
                                        ('/(fr)', Index),
                                        ('/film/(.*)', DetailFilm),
                                        ('/films/(.*)', FilmsByGenre),
                                        ('/films', Films),
                                        ('/proxyimagesimdb', ProxyImagesImdb),
                                        ('/login', Login),
                                        ('/newfilm', NewFilm),
                                        ('/vocabulary/(.*)/(edit)/', VocabularyAction),
                                        ('/vocabulary/(.*)/(new)/', VocabularyAction),
                                        ('/vocabulary/(.*)/(delete)/', VocabularyAction),
                                        ('/vocabulary/(.*)/(save)/', VocabularyAction),
                                        ('/vocabulary/tags/(.*)/(en)', VocabularyListByTags),
                                        ('/vocabulary/tags/(.*)/(de)', VocabularyListByTags),
                                        ('/vocabulary/tags/(.*)/(fr)', VocabularyListByTags),
                                        ('/vocabulary/favourites/(en)', VocabularyFavourite),
                                        ('/vocabulary/favourites/(de)', VocabularyFavourite),
                                        ('/vocabulary/favourites/(fr)', VocabularyFavourite),
                                        ('/vocabulary/printable/(de)', Printable),
                                        ('/vocabulary/printable/(fr)', Printable),
                                        ('/vocabulary/printable/(en)', Printable),
                                        ('/vocabulary/(.*)/(en)', VocabularyListByType),
                                        ('/vocabulary/(.*)/(de)', VocabularyListByType),
                                        ('/vocabulary/(.*)/(fr)', VocabularyListByType),
                                        ('/vocabulary', VocabularyListRedirect),
                                        ('/vocabulary/(en)', VocabularyList),
                                        ('/vocabulary/(de)', VocabularyList),
                                        ('/vocabulary/(fr)', VocabularyList),
                                        ('/tags/(.*)/(edit)/', TagAction),
                                        ('/tags/(.*)/(new)/', TagAction),
                                        ('/tags/(.*)/(delete)/', TagAction),
                                        ('/tags/(.*)/(save)/', TagAction),
                                        ('/tags', TagListRedirect),
                                        ('/tags/(all)', TagList),
                                        ('/tags/(en)', TagList),
                                        ('/tags/(de)', TagList),
                                        ('/tags/(fr)', TagList),
                                        ('/people/(.*)/', DetailPerson),
                                        ('/people/(.+)', DetailPerson),
                                        ('/editfilm/(.*)', EditFilm),
                                        ('/deletefilm/(.*)' , DeleteFilm)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)



def profile_main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats
 prof = cProfile.Profile()
 prof = prof.runctx("real_main()", globals(), locals())
 print "<pre>"
 stats = pstats.Stats(prof)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(80)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 print "</pre>"

if __name__ == "__main__":
  real_main()
